from django.shortcuts import render
from apps.order.utils.views import LoginRequiredJSONMixin
from django.views import View
import json
from django_redis import get_redis_connection
from django.http import JsonResponse
from apps.areas.models import House
from apps.order.models import Order
# Create your views here.
from datetime import datetime

# 1.添加订单
# class OrdersView(LoginRequiredJSONMixin,View):
class OrdersView(LoginRequiredJSONMixin,View):

# class OrdersView(View):
    def post(self,request):
        # 获取用户信息
        # user = request.user
        # user = User()
        # user.id=2
        # 接受参数
        dict=json.loads(request.body.decode())
        # 提取参数
        house_id=dict.get('house_id')
        # house_id=5
  
        start_date=dict.get('start_date')
        end_date=dict.get('end_date')
        # d1 = datetime.datetime.strptime(start_date,'%Y-%m-%d')
        # d2 =datetime.datetime.strptime(end_date,'%Y-%m-%d')
        # days = (d2-d1).days
        # start_date=data.get('start_date')
        #end_date=data.get('end_date')
        # 通过house ID
        # house = House.objects.get(id=house_id)
        # house_price=house.price
        # amount=house_price*days
        # status=0

        # 验证数据
        if not all([house_id,start_date,end_date]):
            return JsonResponse({'code':400,'errmsg':'请选择预定房间号或者预定时间'})
        # 数据入库
        # ①.链接redis
        # redis_cli=get_redis_connection('orders')
        # ②操作hash
        # redis_cli.hset('orders_%s'%user.id,house_id,start_date,end_date)
        try:
            start_date=datetime.strptime(start_date,'%Y-%m-%d')
            end_date=datetime.strptime(end_date,'%Y-%m-%d')
            days = (end_date - start_date).days + 1 
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '订单时间格式错误'}) 
        try:
            house = House.objects.get(pk=house_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '该房屋不存在'})
        if days > house.max_days or days < house.min_days:
            return JsonResponse({'code': 400, 'errmsg': '预定天数超过上限或者下限'})
        # 判断同时间上冲突订单数
        try:
            count = Order.objects.filter(house_id=house_id, begin_date__lte=end_date, end_date__gte=start_date).count()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '订单时间格式错误'})
        if count > 0:
            return JsonResponse({'code': 400, 'errmsg': '订单时间出现冲突'})
        try:
            order = Order.objects.create(
                # user=request.user,
                user=user,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house_price,
                amount=amount,
                status=status
            )
            house.order_count +=1
            order.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '保存到数据库出错'})
        # 返回响应

        data = {
            'order_id': order.id
        }
        return JsonResponse({"errno": "0","errmsg": "下单成功",'data':data})

# 2.获取订单列表
# class OrdersSubmitView(LoginRequiredJSONMixin,View):

# class OrdersSubmitView(LoginRequiredJSONMixin,View):
    def get(self,request):
        # 获取用户信息
        # user=request.user
        # user=User()
        # user.id=2
         # 获取订单信息
        role = request.GET.get('role')
        if role =='custom':
            try:
                orders_list = request.user.orders.filter(status__lte=6).order_by('-id')
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '链接数据库错误'})

            orders = []
            for order in orders_list:
                    orders.append({
                        "amount": order.amount,
                        "comment": order.comment,
                        "ctime": datetime.strftime(order.create_time, '%Y-%m-%d'),
                        "days": order.days,
                        "start_date": order.begin_date,
                        "end_date": order.end_date,
                        "img_url": QINIU_URL + order.house.index_image_url,
                        "order_id": order.id,
                        "status": Order.ORDER_STATUS_ENUM[order.status],
                        "title": order.house.title
                    })
            # 返回响应
            return JsonResponse({'data': {'orders': orders}, 'errno': 0, 'errmsg': 'ok'})

        elif role =='landlord':

            try:
                house_list = House.objects.filter(user=request.user)
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '获取mysql数据出错'})

            try:
                orders = []
                for house in house_list:
                    orders_list = Order.objects.filter(house=house)
                    for order in orders_list:
                        orders.append({
                            "amount": order.amount,
                            "comment": order.comment,
                            "ctime": datetime.strftime(order.create_time, '%Y-%m-%d'),
                            "days": order.days,
                            "start_date": order.begin_date,
                            "end_date": order.end_date,
                            "img_url": QINIU_URL + order.house.index_image_url,
                            "order_id": order.id,
                            "status": Order.ORDER_STATUS_ENUM[order.status],
                            "title": order.house.title
                        })
            except Exception as e:
                return JsonResponse({'errno': 400,
                                     'errmsg': '获取mysql数据出错'})
            return JsonResponse({'data': {'orders': orders}, 'errno': 0, 'errmsg': 'ok'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '参数错误或缺少'})




# 3.接单和拒单
# class StatusOrderView(LoginRequiredJSONMixin,View):
class StatusOrderView(LoginRequiredJSONMixin,View):
    def put(self,request,order_id):
        # 接受请求
        data=json.loads(request.body.decode())
        # 提取参数
        orderinfo=Order.objects.get(id=order_id)
        # 标识符
        action=data.get('action')
        # 获取状态
        # user = request.user
        # 接单
        #if action == 'accept':
            # status=4
            #orderinfo.status = 1
            #orderinfo.save()
        # 拒单
        #elif action == 'reject':
            #comment=data.get('reason')
           # orderinfo.status = 6
           # orderinfo.comment=comment
           # orderinfo.save()

        #return JsonResponse({"errno": "0","errmsg": "操作成功"})
        reason = data.get('reason')
        # 接单
        if action == 'accept':
            try:
                Order.objects.filter(pk=order_id).update(
                    status=3,
                )
            except Exception as e:
                return JsonResponse({'code': 400, 'errmsg': '链接到数据库出错'})
            return JsonResponse({'errno': 0, 'errmsg': '操作成功'})
        # 拒单
        elif action == 'reject':
            try:
                order = Order.objects.get(pk=order_id)
                order.status = 6
                order.comment = reason
                # 拒单后修改house订单个数
                order.house.order_count -= 1
                order.house.save()
                order.save()
            except Exception as e:
                return JsonResponse({'code': 400, 'errmsg': '链接到数据库出错'})

            return JsonResponse({'errno': 0, 'errmsg': '操作成功'})
        # 参数错误
        else:
            return JsonResponse({'errno': 400, 'errmsg': '参数错误或者缺少'})

# 4.评论订单
# class CommentOrderView(LoginRequiredJSONMixin,View):
class CommentOrderView(LoginRequiredJSONMixin,View):
    def put(self,request,order_id):
        # 接受请求
        data = json.loads(request.body.decode())
        # 提取参数
        comment = data.get('comment')
        #orderinfo = Order.objects.get(id=order_id)
        #house=orderinfo.house
        # 订单状态
        #orderinfo.status = 4
        #orderinfo.comment = comment
        #house.order_count += 1
        #orderinfo.house=house
        #orderinfo.save()
        if not comment:
            return JsonResponse({'errno': 400, 'errmsg': '缺少参数'})
        try:
            Order.objects.filter(pk=order_id).update(
                status=4,
                comment=comment
            )
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '链接到数据库出错'})
        # 返回响应
        return JsonResponse({"errno": "0", "errmsg": "评论成功"})